﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using Vit.Web.Services;
using Vit.Web.Models;
using Vit.Web.Mvc.Results;

namespace Vit.Web.Mvc.Filters
{
    public class AuthorizationFilter : IAuthorizationFilter
    {
        private RouteCollection routes;
        private IAccountService account;
        private WebSite site;

        public AuthorizationFilter(RouteCollection routes, WebSite site, IAccountService account)
        {
            this.routes = routes;
            this.site = site;
            this.account = account;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                string url = string.Format("/Member/Account/LogOn?return={0}", filterContext.HttpContext.Request.Url.AbsolutePath);
                filterContext.Result = new RedirectResult(url);
            }
            else
            {
                string area = filterContext.RouteData.DataTokens["area"] as string ?? "";
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                string siteName = site.Name;
                User user = account.GetCurrentUser();
                if (!account.CheckUserPermission(user, siteName, area, controller, action))
                {
                    filterContext.Result = new PartialUnauthorizedResult();
                }
            }
        }
    }
}
